<?php
namespace app\live\controller;

use app\common\model\live\GoodsModel;
use app\common\model\live\AskModel;
use app\common\model\live\PayModel;
use app\common\model\live\RoomFileModel;
use app\common\model\live\RoomModel;
use app\common\model\live\RoomNoticeModel;
use app\common\model\live\RoomVideoModel;
use app\common\model\vod\VideoModel;
use tencentcloud\Im;
use think\facade\Cookie;
use think\facade\Filesystem;

class RoomController extends BaseController
{

  private $roomLogin;
  private $roomModel;
  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->roomLogin = $this->getRoomLogin();
    $this->roomModel = new RoomModel();
  }

  /**
   * 主播页，逻辑全在前端
   * @return string
   * @throws \Exception
   */
  public function index() {
    $trtcConfig = config('cloud.tencent.trtc');
    $roleType = [
        'host'=>'主持人',
        'guests'=>'嘉宾',
        'assistant'=>'助理',
    ];
    $roomId = $this->roomLogin['room_id'];
    $roomInfo = $this->roomModel->where('room_id',$roomId)->find();
    if(empty($roomInfo)) abort(500,'没有找到直播间信息！');
    $roomInfo['host_userid']  = "host" . md5_16($roomId . $roomInfo['host_name']);
    //dump($this->roomLogin);
    $playUrl = $this->roomModel->getPlayUrl($roomId,$roomInfo['host_name']);
    /*获取公告*/
    $notice = RoomNoticeModel::where("room_id",$roomId)->order('id', 'desc')->find();
    /*获取视频*/
    $fileList  = RoomVideoModel::where('room_id',$roomId)->column('file_id');
    $videoList = [];
    if(!empty($fileList)){
      $vodModel = new VideoModel();
      $videoList = $vodModel->getVideoInfos($fileList);
    }
    $tpl = $this->request->isMobile() ? 'mobile_index' : 'index';
    $this->assign('video_list',$videoList);
    $this->assign('notice',$notice);
    $this->assign('play_url',$playUrl);
    $this->assign('room_info',$roomInfo);
    $this->assign('role_type',$roleType[$this->roomLogin['identity']]);
    $this->assign('trtc_config',$trtcConfig);
    $this->assign('room_login',$this->roomLogin);
    return $this->fetch($tpl);
  }


  /**
   * 退出直播间
   */
  public function logout(){
    if($this->roomLogin['identity']=='host'){ //清空在线人数
      $imModel = new Im();
      $imModel->destroyGroup($this->roomLogin['room_id']);
      D('live.Online')->del($this->roomLogin['room_id']);
      D('live.Zan')->del($this->roomLogin['room_id']);
      //清空聊天记录
      D('live.Chat')->del($this->roomLogin['room_id']);
      //清空在线人数
      D('live.Online')->mOnlinedel($this->roomLogin['room_id']);
      $this->roomModel->where('room_id',$this->roomLogin['room_id'])->update(['room_status'=>2]);
    }
    Cookie::delete('anchor_login');
    $this->success('操作成功!');
  }
  /**
   * 设置白板状态
   */
  public function setBoardstatus(){
    $data = $this->request->param();
    $this->roomModel->where('room_id',$data['room_id'])->update(['board_status'=>$data['board_status']]);
    $this->success('状态更新');
  }
  /*设置直播状态，*/
  public function setLivestatus(){
    $data = $this->request->param();
    $this->roomModel->where('room_id',$data['room_id'])->update(['room_status'=>$data['room_status']]);
    $this->success('状态更新');
  }

  /*设置主视频userId*/
  public function setMainStream(){
    $data = $this->request->param();
    $this->roomModel->where('room_id',$data['room_id'])->update([
        'main_userid'=>$data['user_id']
    ]);
    $this->success('状态更新');
  }

  /*获取问答列表*/
  public function getAsklist(){
    $roomId = $this->request->param('room_id');
    $askModel = new AskModel();
    $list = $askModel->where('room_id',$roomId)->order('status asc,create_time desc')->select();
    $list = $list->isEmpty()?[]:$askModel->_formatList($list);
    $todoNum = $askModel->where('room_id',$roomId)->where('status',0)->count();
    return ['list'=>$list,'todo_num'=>$todoNum,'total'=>count($list)];
  }

  /*获取新的问答数量*/
  public function getAsknum(){
    $roomId = $this->request->param('room_id');
    $askModel = new AskModel();
    $todoNum = $askModel->where('room_id',$roomId)->where('status',0)->count();
    return $todoNum;
  }

  /**
   * 解答问题
   * @throws \Exception
   */
  public function answer(){
    $data = $this->request->param();
    $this->validate($data, [
        'answer_content|解答内容' => 'require',
    ]);
    $data['answer_name'] = $this->roomLogin['nick'];
    $data['status'] = 1;
    $askModel = new AskModel();
    $askModel->edit($data);
    $this->success('提交成功');
  }

  /*获取商品列表*/
  public function getGoodsList(){
    $roomId = $this->request->param('room_id');
    $goodsModel = new GoodsModel();
    $list = $this->getList('live.Goods',[],['order'=>'is_current desc,is_sale desc,show_order asc'],['room_id'=>$roomId]);
    $list = empty($list)?[]:$goodsModel->_formatList($list);
    return $list;
  }

  /**
   * 修改商品状态
   * @throws \Exception
   */
  public function changeGoods(){
    $goodsModel = new GoodsModel();
    $imModel = new Im();
    $data = $this->request->param();
    $goodsInfo = $goodsModel->where('id',$data['id'])->find();
    if(empty($goodsInfo)) abort(500,'商品信息不存在');
    if($data['filed'] == 'is_current'){
      $goodsModel->where('room_id',$data['room_id'])->update([$data['filed']=>0]);
    }
    if($data['filed'] == 'is_sale' && $data['value']!=1 && $goodsInfo['is_current']==1){
      $goodsModel->where('id',$data['id'])->update(['is_current'=>0]);
    }
    if($data['filed'] == 'goods_stock'){
      $goodsModel->where('id',$data['id'])->update(['is_sale'=>1,'goods_stock'=>($goodsModel['goods_stock']+$data['value'])]);
    }else{
      $goodsModel->where('id',$data['id'])->update([$data['filed']=>$data['value']]);
    }
    //发送刷新商品消息
    $imModel->sendGroupMsg($data['room_id'],[
        [
            'MsgType'=>'TIMCustomElem',
            "MsgContent"=>[
                "Data"=>json_encode(["type"=>"goods_refresh"],JSON_UNESCAPED_UNICODE)
            ]
        ]
    ]);
    $this->success('设置成功');
  }

  /*获取商品列表*/
  public function getOrderList(){
    $roomId = $this->request->param('room_id');
    $payModel = new PayModel();
    $list = $this->getList('live.Pay',[],['order'=>'is_pay asc,create_time asc'],['room_id'=>$roomId,'pay_type'=>3]);
    $list = empty($list)?[]:$payModel->_formatList($list);
    return $list;
  }

  /*上传图片*/
  public function uploadImg(){
    $driver = $this->request->param('driver', config('filesystem.default'));
    $config   = config("filesystem.disks.{$driver}");
    $file  = $this->request->file();
    $saveName   = Filesystem::disk($driver)->putFile('upload', $file['file']);
    $domain = isset($config['cdn']) ? $config['cdn'] : $config['domain']; //优先使用cdn
    $fileUrl = $domain . '/' . str_replace('\\', '/', $saveName);
    if($driver=='cos') $fileUrl = $config['scheme'].'://'.$fileUrl; //腾讯上传补充前缀
    $this->success('上传成功','',$fileUrl);
  }

  /*
   * 上传文件入库
   */
  public function upFile(){
    $res = $this->request->param();
    $fileModel = new RoomFileModel();
    $data['room_id'] = $res['room_id'];
    $data['file_id'] = $res['file_id'];
    $data['file_url'] = $res['resultUrl'];
    $data['file_title'] = $res['title'];
    $data['file_pages'] = $res['pages'];
    $data['file_resolution'] = $res['resolution'];
    $fileModel->add($data);
    $this->success('操作成功');
  }

  /*
   * 上传文件删除
   */
  public function delFile(){
    $fileId = $this->request->param('file_id');
    $fileModel = new RoomFileModel();
    $fileModel->del($fileId);
    $this->success('操作成功');
  }
}